import React, { Component } from 'react'
import { Card, Form, Input, Button, Cascader, Row, Col, Upload, Modal, message } from 'antd';
import { addTypesList, getTypesList } from '../../api/productsList';
import { PlusOutlined } from '@ant-design/icons';

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
const success = (msg) => {
    message.success(msg);
  };
export default class AddList extends Component {
    state = {
        options: [],


        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [],
        addInfo: {},
        type: ''
    }
    componentDidMount() {
        this.getTypesList()
    }
    // 获取列表
    getTypesList = async () => {
        const res = await getTypesList()
        if (res.code) {
            this.setState({
                options: res.data
            })
        }
    }
    // 获取type的id值
    onChange = (value, selectedOptions) => {
        this.setState({
            type: selectedOptions[1].id
        })
    }


    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleChange = ({ fileList, file }) => {
        console.log(file);
        this.setState({
            addInfo: {
                ...this.state.addInfo,
                imgSrc: file.name
            },
            fileList
        })
    }

    render() {
        // 点击提交时候触发
        const onFinish = (values) => {
            // console.log('Success:', values);
            // console.log(this.state.addInfo);
            this.setState({
                addInfo: {
                    ...values,
                    ...this.state.addInfo,
                    type: this.state.type
                }
            },
                async() => {
                    const res = await addTypesList(this.state.addInfo)
                      if(res.code){
                        success(res.msg)
                        this.props.history.push("/products/list")
                      }
                }
            )
        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };


        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <Card title="添加商品" extra={<a href="#">More</a>}>
                <Row>
                    <Col span={10}>
                        <Form
                            name="basic"
                            labelCol={{
                                span: 8,
                            }}
                            wrapperCol={{
                                span: 16,
                            }}
                            initialValues={{
                                remember: true,
                            }}
                            onFinish={onFinish}
                            onFinishFailed={onFinishFailed}
                            autoComplete="off"
                        >
                            <Form.Item
                                label="商品名字"
                                name="name"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please input your name!',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="商品描述"
                                name="title"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please input your title!',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="价格"
                                name="price"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please input your title!',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="分类"
                                name="type"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please input your type!',
                                    },
                                ]}
                            >
                                <Cascader
                                    options={this.state.options}
                                    expandTrigger="hover"
                                    onChange={this.onChange}
                                />
                            </Form.Item>
                            <Form.Item
                                label="商品详情"
                                name="msg"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please input your type!',
                                    },
                                ]}
                            >
                                <Input.TextArea />
                            </Form.Item>

                            <Form.Item
                                name="imgSrc"
                                wrapperCol={{
                                    offset: 10,
                                    span: 12,
                                }}
                            >
                                <Upload
                                    action="http://web.woniulab.com:8002/goods/fileUpload"
                                    listType="picture-card"
                                    fileList={fileList}
                                    onPreview={this.handlePreview}
                                    onChange={this.handleChange}
                                    name='imgSrc'
                                >
                                    {fileList.length >= 1 ? null : uploadButton}
                                </Upload>
                                <Modal
                                    visible={previewVisible}
                                    title={previewTitle}
                                    footer={null}
                                >
                                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                </Modal>
                            </Form.Item>

                            <Form.Item
                                wrapperCol={{
                                    offset: 12,
                                    span: 12,
                                }}
                            >
                                <Button type="primary" htmlType="submit" >
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>
                    </Col>
                </Row>

            </Card>
        )
    }
}
